/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.menuItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.BaseObject;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentFieldValue;
import com.blandware.atleap.model.core.ContentImage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.service.core.RoleManager;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.service.exception.ParentItemNotFoundException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MenuItemForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Creates new menu item
 * </p>
 * <p><a href="CreateMenuItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.40 $ $Date: 2008/04/29 17:48:09 $
 * @struts.action path="/core/menuItem/create"
 * name="menuItemForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-menuItem-create"
 * @struts.action-forward name="inputForward"
 * path=".core.menuItem.create"
 * @struts.action-forward name="listMenuItems"
 * path="/core/menuItem/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/menuItem/list.do"
 */
public final class CreateMenuItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setAttribute("linkTargets", WebappConstants.LINK_TARGETS);

		MenuItemForm menuItemForm = (MenuItemForm) form;
		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(menuItemForm.getOwnerId()) ) {
			ownerId = Long.valueOf(menuItemForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		MenuManager menuManager = (MenuManager) getBean(Constants.MENU_MANAGER_BEAN);

		if ( !isCancelled(request) ) {

			MenuItem menuItem = new MenuItem();

			// create refs
			List linkedPages = new ArrayList();
			List linkedResources = new ArrayList();
			List roles = null;
			boolean titleIsSet = WebappUtil.hasCorrectValues(menuItemForm.getTitleMap());
			boolean toolTipIsSet = WebappUtil.hasCorrectValues(menuItemForm.getToolTipMap());
			String image = menuItemForm.getImage();
			BaseObject linkedObject = WebappUtil.lookupObject(image, request.getSession().getServletContext(), request.getContextPath(), request);
			if ( linkedObject != null && linkedObject instanceof ContentImage ) {
				linkedResources.add(linkedObject);
			}

			String altImage = menuItemForm.getAltImage();
			if ( !GenericValidator.isBlankOrNull(altImage) && !altImage.equals(image) ) {
				linkedObject = WebappUtil.lookupObject(menuItemForm.getAltImage(), request.getSession().getServletContext(), request.getContextPath(), request);
				if ( linkedObject != null && linkedObject instanceof ContentImage ) {
					linkedResources.add(linkedObject);
				}
			}

			linkedObject = WebappUtil.lookupObject(menuItemForm.getLocation(), request.getSession().getServletContext(), request.getContextPath(), request);
			if ( linkedObject != null ) {
				if ( linkedObject instanceof ContentResource ) {
					ContentResource resource = (ContentResource) linkedObject;
					roles = new ArrayList(resource.getRoles());
					linkedResources.add(resource);
				} else if ( linkedObject instanceof Page ) {
					Page page = (Page) linkedObject;
					linkedPages.add(page);

					// fill in title and tool tip
					if ( !titleIsSet ) {
						ContentField titleField = (ContentField) page.getContentFieldsMap().get("title");
						List titleValues = titleField.getContentFieldValues();
						for ( Iterator i = titleValues.iterator(); i.hasNext(); ) {
							ContentFieldValue value = (ContentFieldValue) i.next();
							menuItemForm.setTitle(value.getContentLocale().getIdentifier(), value.getSimpleValue());
						}
						titleIsSet = true;
					}

					if ( !toolTipIsSet ) {
						ContentField descriptionField = (ContentField) page.getContentFieldsMap().get("description");
						if ( descriptionField != null ) {
							List descriptionValues = descriptionField.getContentFieldValues();
							for ( Iterator i = descriptionValues.iterator(); i.hasNext(); ) {
								ContentFieldValue value = (ContentFieldValue) i.next();
								menuItemForm.setToolTip(value.getContentLocale().getIdentifier(), value.getSimpleValue());
							}
							toolTipIsSet = true;
						}
					}

					// set roles
					if ( page instanceof ContentPage ) {
						ContentPage cp = (ContentPage) page;
						roles = new ArrayList(cp.getRoles());
					} else if ( page instanceof ActionPage ) {
						ActionPage ap = (ActionPage) page;
						String[] roleNames = WebappUtil.getAPRoleNames(ap.getUri(), request);
						roles = new ArrayList();
						RoleManager roleManager = (RoleManager) getBean(Constants.ROLE_MANAGER_BEAN);
						for ( int i = 0; i < roleNames.length; i++ ) {
							String roleName = roleNames[i];
							Role role = roleManager.retrieveRole(roleName);
							if ( role != null ) {
								roles.add(role);
							} else {
								// can it happen?
								if ( log.isWarnEnabled() ) {
									log.warn("Role with name '" + roleName + "', specified for Action with URI '" + ap.getUri() + "' could not be found. Skipped.");
								}
							}
						}
					}
				}
			} else {
				// set external location flag
				menuItem.setExternalLocation(Boolean.TRUE);
			}

			if ( !titleIsSet ) {
				// title must be specified
				ActionMessages errors = new ActionMessages();
				errors.add("title", new ActionMessage("core.commons.errors.required", getMessage(request, "core.menuItem.form.title")));
				saveErrors(request, errors, false);
				saveToken(request);
				return mapping.getInputForward();
			}

			Long parentItemId = (Long) request.getSession().getAttribute(WebappConstants.MENU_ITEM_PARENT_ID_KEY);

			menuItem.setLinkedResources(linkedResources);
			menuItem.setLinkedPages(linkedPages);
			menuItem.setRoles(roles);

			WebappUtil.copyProperties(menuItem, menuItemForm, request);
            WebappUtil.fillFieldValueWithDefaultLocaleValue(menuItemForm.getTitleMap(), menuItem.getTitle(), servlet.getServletContext());
            menuItem.setTitle(menuItemForm.getTitleMap());
            WebappUtil.copyFieldValue(menuItem.getToolTip(), menuItemForm.getToolTipMap());
            menuItem.setOrigItem(null);
			menuItem.setIdentifier(null);
			menuItem.setPosition(null);

			// set to null properties related only to hard-coded elements

			menuItem.setAnchor(null);
			menuItem.setAction(null);
			menuItem.setForward(null);
			menuItem.setOnmouseover(null);
			menuItem.setOnmouseout(null);
			menuItem.setOnclick(null);

			// set to default properties which were not specified in form
			if ( GenericValidator.isBlankOrNull(menuItemForm.getStyle()) ) {
				menuItem.setStyle(null);
			}

			if ( GenericValidator.isBlankOrNull(menuItemForm.getStyleClass()) ) {
				menuItem.setStyleClass(null);
			}

			if ( GenericValidator.isBlankOrNull(menuItemForm.getAlign()) ) {
				menuItem.setAlign(null);
			}

			if ( GenericValidator.isBlankOrNull(menuItemForm.getImage()) ) {
				menuItem.setImage(null);
			}

			if ( GenericValidator.isBlankOrNull(menuItemForm.getAltImage()) ) {
				menuItem.setAltImage(null);
			}


			try {
				menuManager.createMenuItem(menuItem, parentItemId, ownerId);
			} catch ( OwnerNotFoundException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.menuItem.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			} catch ( ParentItemNotFoundException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("parentItemNotFound", new ActionMessage("core.menuItem.errors.parentItemNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("listMenuItems");
			}

		}

		// flush cache
		CacheUtil cacheUtil = CacheUtil.getInstance(request);
		cacheUtil.flushMenuCache();
		cacheUtil.flushContentPageCache();

		return mapping.findForward("listMenuItems");
	}
}